﻿using System;
using System.Configuration;
using System.IO;
using System.Net;
using System.Net.Mail;
using System.Text;
using System.Web.Hosting;
namespace Smatime.Web.Common
{
    public class EmailHelper
    {
        private static EmailHelper _instane;
        private readonly MailMessage _mailMessage;
        private readonly SmtpClient _smtpClient;
        private EmailHelper()
        {
            var networkCred = new NetworkCredential
            {
                UserName = ConfigurationManager.AppSettings["Email"],
                Password = ConfigurationManager.AppSettings["Password"]
            };
            _smtpClient = new SmtpClient
            {
                Port = int.Parse(ConfigurationManager.AppSettings["MailPort"]),
                Host = ConfigurationManager.AppSettings["MailServer"],
                EnableSsl = bool.Parse(ConfigurationManager.AppSettings["IsSSLEnabled"]),
                Timeout = int.Parse(ConfigurationManager.AppSettings["TimeOut"]),
                DeliveryMethod = SmtpDeliveryMethod.Network,
                UseDefaultCredentials = true,
                Credentials = networkCred
            };

            _mailMessage = new MailMessage
            {
                From = new MailAddress(ConfigurationManager.AppSettings["Email"]),
                BodyEncoding = Encoding.UTF8,
                IsBodyHtml = true,
                DeliveryNotificationOptions = DeliveryNotificationOptions.OnFailure
            };
        }

        public static EmailHelper GetInstance()
        {
            return _instane ?? (_instane = new EmailHelper());
        }

        public bool SendForgotPasswordEmail(string email, string accessCode)
        {
            try
            {
                // LH: Read Email template from VAR in accessCode 
                var emailTemplate =
                    HostingEnvironment.MapPath(ConfigurationManager.AppSettings["ForgotPasswordEmailTemplate"]);
                if (emailTemplate == null)
                {
                    return false;
                }
                var reader = new StreamReader(emailTemplate);
                var readFile = reader.ReadToEnd();
                var strContent = readFile;
                strContent = strContent.Replace("[Email_Account]", email).Replace("[Reset_Code]", accessCode);
                // END
                _mailMessage.Body = strContent;
                _mailMessage.Subject = ConfigurationManager.AppSettings["ForgotPasswordEmailSubject"];
                _mailMessage.To.Add(email);
                // LH: Send email to client
                _smtpClient.Send(_mailMessage);
                // END
                return true;
            }
            catch (Exception ex)
            {
                return false;
            }
        }
    }
}